import {getCurrentPageUrl} from '../../../utils/util.js';
const FN = require('../../../utils/public');
import commonAPI from '../../../api/api'
import allocationclassrecordAPI from '../../../api/allocationclassrecordAPI.js'
import { configApp } from '../../../utils/config'
var app = getApp();
const qiniuUploader = require("../../../utils/qiniuUploader");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    stuInfo: {},// 学员信息
    classInfo: {},// 班级信息
    evadingAudit: {},
    priTmplIdArr: [],
    sessionId4openId: null,
    btnstatus: 1
  },

  /**
   * 生命周期函数--监听页面加载
   * 
   * 1. 第一步，先查询用户是否已经存在该班级，如果存在则把用户信息直接展示出来
   * 2. 查询班级信息，
   * 3. 提交保存，如果用户是首次，则需要把用户信息同步到student表，然后在插入分班表
   * 4. 给老师发送审核消息提醒，验证是否通过该学员加入班级。
   */
  onLoad: function (options) {
    this.initOthderData();// 用于显隐页面
    this.getSubscribeMsg();// 订阅消息
    this.getQrcodeInfo(options.scene);// 获取班级信息
  },


  /*
    1. 隐藏相关字段
    */
  initOthderData() {
    var that = this;
    wx.setClipboardData({data: 'data',success (res) {}})
    setTimeout(function () {
      that.setData({
        evadingAudit: app.globalData.evadingAudit,
      })
    }, 1000)
  },

  // 获取订阅消息
  getSubscribeMsg: function () {
    var that = this;
    commonAPI.getSubscribeMsg({ pageUrl: getCurrentPageUrl() }).then(res => {
      if (res.code == '200' && res.data.length > 0) {
        var arr = res.data[0].priTmplIdArr.split(",")
        that.setData({
          priTmplIdArr: arr
        })
      }
    })
  },

  // 获取小程序码信息 
  getQrcodeInfo: function (wdclassid) {
    var that = this;
    commonAPI.getClassById({ wdclassid }).then(res => {
      if (res.code == '200') {
        if (res.data.claObj.wdclassStatus == '0') {
          FN.Toast('班级已不存在');
          that.setData({
            btnstatus: 3
          })
        } else {
          that.setData({
            stuInfo: res.data
          });
          if (res.data.hasBindWX) {
            that.setData({
              btnstatus: 2
            })
          }
        }
        if(res.data.stuInfo==null){
          res.data.stuInfo = {
            avatarUrl: app.globalData.userInfo.signInfo?.avatarUrl || '',
            nickName: app.globalData.userInfo.signInfo?.nickName || ''
        }
        }
        that.setData({
          stuInfo: res.data.stuInfo,
          classInfo: res.data.claObj
        });
        console.log(that.data.stuInfo)
        if (res.data.hasBindWX) {
          that.setData({
            btnstatus: 2
          })
        }
      }
    })
  },

  // 订阅消息
  subscribeMessage: function (e) {
    var that = this;
    wx.requestSubscribeMessage({
      tmplIds: that.data.priTmplIdArr,
      success(res) {
      }
    })
    this.saveUserInfo(e)
  },

  // 先验证换取学员信息的口令token是否过期 joinClassByQrcode
  saveUserInfo: function (e) {
    var that = this;
    var frmData = e.detail.value;
    if (that.checkedStuData(frmData)) {
      var data = frmData;
      data.source = "1002";
      allocationclassrecordAPI.joinClassByQrcode({ ...data,...that.data.classInfo }).then(res => {
        if (res.data == 1) {
          FN.Toast('绑定成功！');
          that.setData({
            btnstatus: 2
          })
          setTimeout(function () {
            // 跳转到首页
            wx.switchTab({
              url: '../../index/index'
            })
          }, 1000);
        }
      })
    }
  },

  checkedStuData: function (frmData) {
    var a = /[0-9]/;
    if (frmData.nickName == "") {
      FN.Toast('姓名里不能为空')
      return false;
    } else if (a.test(frmData.nickName)) {
      FN.Toast('姓名里不能包含数字')
      return false;
    } else if (frmData.studentTel.length != 11) {
      FN.Toast('手机号格式有误！')
      return false;
    } else {
      return true;
    }
  },

  initQiniu: function () {
    var options = {
      region: 'ECN',
      uptokenURL: configApp.api_base_url + 'qiniu/getUploadToken',
      domain: configApp.qiniuBucketURLPrefix,
      shouldUseQiniuFileName: true
    }
    // 将七牛云相关配置初始化进本sdk
    qiniuUploader.init(options);
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.uploadUserHeaderImg(avatarUrl)
  },

  uploadUserHeaderImg(avatarUrl) {
    var that = this, filePath = avatarUrl, fileName = "avatarUrl" + new Date().getTime() + ".png";
    this.initQiniu();
    // 向七牛云上传
    qiniuUploader.upload(filePath, (res) => {
      res.fileName = fileName;
      if (res.hasOwnProperty("error")) {
        FN.Toast('上传失败，请重新上传');        
        that.initQiniu();
      } else {
        const avatarUrl = 'stuInfo.avatarUrl'
        this.setData({
          [avatarUrl]: res.fileURL
        })
      }
    }, (error) => {
      console.error('error: ' + JSON.stringify(error));
    }, { key: fileName }, (progress) => {
    }, cancelTask => that.setData({ cancelTask })
    );
  },

  // 监听昵称改变
  onChangeNickname(e) {
    let nickName = "stuInfo.nickName"
    this.setData({
      [nickName]: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
})